<?php
/**
 * Created by PhpStorm.
 * User: Winter
 * Date: 2020/6/19 0019
 * Time: 10:27
 */
namespace app\merchant\controller\api;

use app\merchant\model\store\StoreCategory;
use app\merchant\model\store\StoreProduct;
use app\merchant\model\system\SystemAdmin;
use app\Request;
use think\facade\Db;
use crmeb\services\{JsonService, UtilService};

/**
 * 订单管理控制器
 * Class StoreOrder
 * @package app\merchant\controller\store
 */
class Index {
    public function __construct()
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin,Mer-id, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
    }

    /**
     * 获取组件种类
     */
    public function get_components_cate(){
        $data = Db::name('adorn_components')->order('id asc')->select()->toArray();
        foreach ($data as $k=>$v){
            $data[$k]['content'] = use_json_decode($v['content']);
        }
        JsonService::success('OK',$data);
    }

    /**
     * 获取默认装修模板
     */
    public function get_default_template(Request $request){
        $mid = trim(ltrim($request->header('Mer-id')));
        if(!$mid){$mid=1;}
        //判断改用户是否有默认模板
        $is_have     = Db::name('adorn_template')->where('mid',$mid)->count();
        //没有默认模板，添加一个默认模板
        if(!$is_have){
            $insert_all = [];
            $data   = Db::name('adorn_template')
                    ->where('mid',0)
                    ->order('id asc')
                    ->select()
                    ->toArray();
            foreach ($data as $k=>$v){
                unset($data[$k]['id']);
                $data[$k]['mid'] = $mid;
                $insert_all[] = $data[$k];
            }
            Db::name('adorn_template')->insertAll($insert_all);
        }
        $back = Db::name('adorn_template')
            ->field('id,image,is_select,name')
            ->where('mid',$mid)
            ->order('my_sort asc')
            ->select()
            ->toArray();
        JsonService::success('OK',$back);
    }

    /**
     * 获取装修模板详情
     */
    public function get_default_template_detail(Request $request){
        $adorn_template_id = $request->param('template_id');
        $maps['id']  = $adorn_template_id;
        $data        = Db::name('adorn_template')->where($maps)->findOrEmpty();
        if($data){
            $data['content'] = use_json_decode($data['content']);
            JsonService::success('OK',$data);
        }
        JsonService::fail('暂无数据');
    }

    /**
     * 添加模板
     */
    public function add_template(Request $request){
        $content = $request->param('content');
        $image   = $request->param('image');
        $name    = $request->param('name');
        //判断模板名是否重复
        $is_have = Db::name('adorn_template')->where('name',$name)->findOrEmpty();
        if($is_have){
            JsonService::fail('模板名已存在');
        }
        $insert['mid']      = 0;
        $insert['name']     = $name;
        $insert['image']    = $image;
        $insert['content']  = $content;
        $insert['add_time'] = time();
        $result = Db::name('adorn_template')->insert($insert);
        if($result){
            JsonService::success('添加成功');
        }else{
            JsonService::fail('添加失败');
        }
    }
    //更改产品属性
    private function do_change_product($rmbd,$jptj,$sfjp,$cxdp){
        if($rmbd){
            $rmbd_arr = json_decode($rmbd,true); //热门榜单
            $ups0['is_hot'] = 1;
            Db::name('store_product')->where('id','in',$rmbd_arr)->update($ups0);
        }
        if($rmbd){
            $jptj_arr = json_decode($jptj,true);//精品推荐
            $ups1['is_best'] = 1;
            Db::name('store_product')->where('id','in',$jptj_arr)->update($ups1);
        }
        if($rmbd){
            $sfjp_arr = json_decode($sfjp,true); //首发精品
            $ups2['is_new'] = 1;
            Db::name('store_product')->where('id','in',$sfjp_arr)->update($ups2);
        }
        if($rmbd){
            $cxdp_arr = json_decode($cxdp,true); //促销单品
            $ups3['is_benefit'] = 1;
            Db::name('store_product')->where('id','in',$cxdp_arr)->update($ups3);
        }
    }

    /**
     * 修改模板
     */
    public function edit_template(Request $request){
        $adorn_template_id = $request->param('template_id');
        $content           = $request->param('content');
        $rmbd              = $request->param('rmbd');
        $jptj              = $request->param('jptj');
        $sfjp              = $request->param('sfjp');
        $cxdp              = $request->param('cxdp');
        $this->do_change_product($rmbd,$jptj,$sfjp,$cxdp);
        $insert['content']  = $content;
        $insert['add_time'] = time();
        $map['id']          = $adorn_template_id;
        Db::name('adorn_template')->where($map)->update($insert);
        JsonService::success('保存成功');
    }

    /**
     * 启用模板
     */
    public function choose_template(Request $request){
        $adorn_template_id = $request->param('template_id');
        //取消其他的选中
        $mid               = trim(ltrim($request->header('Mer-id')));
        if(!$mid){$mid=1;}
        Db::name('adorn_template')->where('mid',$mid)->update(['is_select'=>0]);
        $insert['is_select'] = 1;
        $insert['add_time'] = time();
        $map['id']          = $adorn_template_id;
        Db::name('adorn_template')->where($map)->update($insert);
        JsonService::success('保存成功');
    }


    /**
     * 获取店铺导航链接
     */
    public function get_navigate_link(){
        $data = Db::name('adorn_link')->select()->toArray();
        JsonService::success('OK',$data);
    }


    /**
     * 获取我的选择模板
     */
    public function get_address(Request $request){
        $mid = trim(ltrim($request->header('Mer-id')));
        if(!$mid){$mid=1;}
        $back   = $this->my_store($mid);
        $url    = $back['store_url'];
        $qrcode = $back['code_url'];
        $select_adorn_template = Db::name('adorn_template')
            ->field('id,image,is_select,name')
            ->where('mid',$mid)
            ->where('is_select',1)
            ->find();
        $data['select_template']    = $select_adorn_template;
        $data['url']                = $url;
        $data['qrcode']             = $qrcode;
        JsonService::success('OK',$data);
    }

    /**
     * 我的店铺
     */
    private function my_store($mer_id){
        $data    = SystemAdmin::get(['id'=>$mer_id])->toArray();
        $name    = "mer_id".$mer_id.".png";
        $codeUrl = $data['store_url'];
        if(!$data['code_url']){
            $imageInfo = UtilService::getQRCodePath($codeUrl, $name);
            SystemAdmin::edit(["code_url"=>$imageInfo['dir']],$data["id"]);
            $data['code_url']= $imageInfo['dir'];
        }
      return $data;
    }

    /**
     * 异步查找产品
     *
     * @return json
     */
    public function product_list_api(Request $request)
    {
        $mid = trim(ltrim($request->header('Mer-id')));
        $where = UtilService::getMore([
            ['page', 1],
            ['limit', 10],
            ['store_name', ''],
            ['cate_id', ''],
            ['excel', 0],
            ['order', ''],
            [['type', 'd'], \request()->param('type/d')]
        ]);
        $where['mer_id'] = $mid;
        return JsonService::successful(StoreProduct::ProductList($where));
    }

    /**
     *  异步获取分类列表
     */
    public function category_list_api(Request $request){
        $mid = trim(ltrim($request->header('Mer-id')));
        $where = UtilService::getMore([
            ['is_show',''],
            ['pid',\request()->param('pid','')],
            ['cate_name',''],
            ['page',1],
            ['limit',20],
            ['order','']
        ]);
        $where["mer_id"] = $mid;
        JsonService::successful(StoreCategory::CategoryList($where));
    }

    /**
     * 修改首页地址
     */
    public function my_store_update(Request $request)
    {
        $mid = trim(ltrim($request->header('Mer-id')));
        if(!$mid){$mid=1;}
        $url = $request->param('url');
        if (!$url) JsonService::fail('首页地址不能为空');
        $update['store_url'] = $url;
        SystemAdmin::edit($update, $mid);
        //跟新二维码
        $name    = "mer_id".$mid.".png";
        UtilService::getQRCodePath($update['store_url'], $name);
        JsonService::successful('修改成功!');
    }

    /**
     * 上传微信配置文件
     */
    public function my_upload(Request $request){
        $mer_id    = trim(ltrim($request->header('Mer-id')));
        $adminInfo = Db::name('merchant_admin')->where('id',$mer_id)->find();
        $is_file   = $adminInfo['is_file'];
        if($is_file){
            JsonService::fail('已经上传过了!');
        }
        // 获取表单上传文件
        $files = request()->file();
        try {
            validate(['file' => 'filesize:10240|fileExt:txt'])
                ->check($files);
            foreach ($files as $file) {
                $fileName = $file->getOriginalName();
                $savename[] = \think\facade\Filesystem::putFileAs('/', $file, $fileName);
            }
            $up['is_file'] = 1;
            Db::name('merchant_admin')->where('id',$mer_id)->update($up);
        }catch (\Exception $e){
            $msg =  $e->getMessage();
            JsonService::fail($msg);
        }
        JsonService::successful('上传成功!');
    }



}